<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--@elvariable id="actionBean" type="com.depo.quiggle.view.controller.QglLogPendingAction"--%>
<%@ include file="/WEB-INF/jsp/include/taglibs.jsp" %>
<script type="text/javascript" src=" ${pageContext.request.contextPath}/js/rateTableForQGL.js" >
 	</script>	 
<script type="text/javascript">
		var actualUserId = '${actionBean.userId}';
        var rateitemcount = 0;
        var reqrtcodes = [];
        var agencies = [

            <c:forEach items="${actionBean.agencies}" var="agency" varStatus="agencyStatus">
            {
                value:"${agency.userId} ${agency.initials} ${agency.firstName} ${agency.lastName}",
                id: "${agency.userId}",
                initial: "${agency.initials}",
                firstName: "${agency.firstName}",
                lastName: "${agency.lastName}"
            }<c:if test="${!agencyStatus.last}">,</c:if>
            </c:forEach>
        ];
        var proofers = [

            <c:forEach items="${actionBean.proofers}" var="proofer" varStatus="prooferStatus">
            {
                value:"${proofer.userId} ${proofer.initials} ${proofer.firstName} ${proofer.lastName}",
                id: "${proofer.userId}",
                initial: "${proofer.initials}",
                firstName: "${proofer.firstName}",
                lastName: "${proofer.lastName}"
            }<c:if test="${!prooferStatus.last}">,</c:if>

            </c:forEach>
        ];

        var scopists = [

            <c:forEach items="${actionBean.scopists}" var="scopist" varStatus="scopistStatus">
            {
                value:"${scopist.userId} ${scopist.initials} ${scopist.firstName} ${scopist.lastName}",
                id: "${scopist.userId}",
                initial: "${scopist.initials}",
                firstName: "${scopist.firstName}",
                lastName: "${scopist.lastName}"
            }<c:if test="${!scopistStatus.last}">,</c:if>
            </c:forEach>
        ];
        
          var rateunits =[

                     <c:forEach items="${actionBean.ratePriceType}" var="rateunit" varStatus="rateunitsts">
                     { 
                         id: "${rateunit.id}",
                         type: "${rateunit.type}"
                     }<c:if test="${!rateunitsts.last}">,</c:if>
                     </c:forEach>
                     ];
          var perrateunits =[

                          <c:forEach items="${actionBean.ratUnitType}" var="rateunit" varStatus="rateunitsts">
                          { 
                              id: "${rateunit.id}",
                              type: "${rateunit.type}"
                          }<c:if test="${!rateunitsts.last}">,</c:if>
                          </c:forEach>
                          ];
        
        function getAllReimbursedServices(jobId,id,type){
        	 $.ajaxSetup({
      		   jsonp: null,
      		   jsonpCallback: null
      		});
			var value= document.getElementById(id).value;
			if(value == "false"){
				var reimid ='';
			  if(type == 'reim')
				  reimid = '#servicereimtext'+jobId;
			  else
				  reimid = '#servicenonreimtext'+jobId;
			  
			     $(reimid).html('No');
				return;
			}
			var reimid ='';
			 if(type == 'reim'){
				  reimid = '#servicereimtext'+jobId;
			 }else{
				  reimid = '#servicenonreimtext'+jobId;
			 }
			 $(reimid).html('<a href="javascript:{}" onclick="getAllReimbursedServices('+jobId+',\''+id+'\',\''+type+'\')">Yes</a>');
			 if($.trim($("#agencyId"+jobId).val()).length == 0 || $.trim($("#agencyId"+jobId).val()) =='0')
 				return;
				var newcodes={code:new Array()}
				getUserMasterRateItems(jobId,type,newcodes,$("#agencyId"+jobId).val(),false);
			 $.ajax({
      		  type:'POST',
      		  url: 'qgl-log-detail-accounting.action?getRateItemsFromJobService',
      		  dataType: 'json',
      		  data: {jobId:jobId,agencyId:$("#agencyId"+jobId).val(),type:type,typeId:$("#typeId"+jobId).val()},
      			 
      		  success: function(result){
      			  rateitemcount = 0;
      			  reqrtcodes = result[1];
      			 $("#servicesreimforminner").html("");
      			  var str = "<div id='allservicreimdiv'>";
				  str +='<div id="allservicreimErrorMSGdiv" class="fontStyle"></div>';
      			str += "<fieldset>";
      		   	str += "<table id='servreimberstable' style='width:100%;text-align: center;'>";
				/*str += '<tbody><colgroup>';
				str += '<col width="1%">';
                str += '<col width="9%">';
                str += '<col width="32%">';
                str += '<col width="9%">';
                str += '<col width="9%">';
                str += '<col width="10%">';
                str += '<col width="9%">';
                str += '<col width="6%">';
                str += '<col width="6%">';
                str += '<col width="8%">';
	            str += '</colgroup>';*/
	            str += '<tr align="left" valign="middle">';
      		    str += "<th align='left' valign='middle' width='1%'><input type='checkbox' name='checkbox' value='checkbox' class='QGLAllcheckboxClass'></th>";
      		   	str += "<th align='left' valign='middle' width='9%'>Code</th>";
      		   	str += "<th align='left' valign='middle' width='28%'>Description</th>";
      		    str += "<th align='left' valign='middle' width='7%'>Quantity</th>";
      			str += "<th align='left' valign='middle' width='7%'>Count</th>";
      		   	str += "<th align='left' valign='middle' width='8%'>Value</th>";
      		   	str += "<th align='left' valign='middle' width='10%'>Unit</th>";
      		   	str += "<th align='left' valign='middle' width='9%'>PerUnit</th>";
      		   	str += "<th align='center' valign='middle' width='6%'>Reimbursable<br>";
				str +="<input type='checkbox' class='checkboxAllReim-QGL' name='checkbox' value='checkbox' /></th>";
      		   	str += "<th align='center' valign='middle' width='6%'>Taxable<br>";
				str += "<input type='checkbox' class='checkboxAllTax-QGL' name='checkbox' value='checkbox' /></th>";
      		    str += "<th align='left' valign='middle' width='8%'>Remove</th>"; 
      			str += "<tbody>"; 
      			
                   if(result != null && result[0].length > 0){
                	   for(var i in result[0]){
                		   str += getNewRateItemRow(result[0][i],'new',$("#typeId"+jobId).val(),jobId,$("#agencyId"+jobId).val());
                		   
                	   }
                   }
                   str += "</tbody>"; 
                   str += " </table>";
                   str += "</fieldset>";
                   str +='<div id="allservicreimErrorMSGdivOuter" ></div>';
                   str += "</div>";
                   $("#servicesreimforminner").html(str);
                  // var buttons = "<input type='button' onclick='getRatesForReimbursment("+jobId+",\""+type+"\")' value='Click To Add From Rate Table'></input> ";
                   //var buttons = "<input type='button' class='addNewRowItemClass' onclick='addNewRowItem(\""+type+"\")' value='Add New '></input> ";
                  // buttons+= "<input type='button' onclick='getUserMasterRateItems("+jobId+",\""+type+"\")' value='Click To Add From Master Rate Table '></input> ";
                  // $("#ratetableview").html(buttons);
                   
                   if(type == 'reim'){
    	        	  
    	        	   $('#servicesreimform').dialog( "option", "title", 'Services Reimbursed');


    	           }else{
    	        	  
    	        	   $('#servicesreimform').dialog( "option", "title", 'Services Non-Reimbursed');


    	           }
                   
                   $( "#servicesreimform").dialog({
                       autoOpen: true,
                       height: 450,
                       width: 920,
                       modal: true,
                       open:function(){
    					   $(".reimjobrateitemcode").live("change",function(){
    							  var flag=ServhighlightDuplicates(".reimjobrateitemcode");
    							  if (!flag){
    							    serviceAutoPopulateMRItem($(this),type);
    							  }
    							});
    					   $(".servdelete").live("click",function(){
    					   	       //ServhighlightDuplicates(".reimjobrateitemcode");						 
    							}); 
    						$(".reimjobrateitemrateunit").live("change",function(){
    						   if($(this).val()==2)
    						   servicesReimexpedite(this);
    						});	
    						$(".reimjobrateitemperunit").live("focus",function(){
    						if($(this).closest("tr").find(".reimjobrateitemrateunit").val()==2)
    						   	   servicesReimexpedite(this);
    						});
    						$(".reimjobrateitemperunit").closest("tbody").live("change",function(){
    								servicesReimexpedite(".reimjobrateitemrateunit");
    						
    						});
    					   },
                       buttons: {
                    	   "Add New": function() {
                    		   addNewRowItem(type);
                           },
                    	   "Click To Add From Master Rate Table": function() {
                    		   
                    		    var codes={code:new Array()}
                    		   $(".rateitemclass").each(function() { 
                        		   if($("#jobrateitemid"+$(this).attr('id')).val() == '0' && $.trim($("#jobrateitemcode"+$(this).attr('id')).val()).length >0)
                        		   {
                        			   var obj1 = {};
                        			   obj1["rateItemCode"] = $("#jobrateitemcode"+$(this).attr('id')).val();
                        			   codes.code.push(obj1);
                        		   }
                        		});
                    		   getUserMasterRateItems(jobId,type,codes,$("#agencyId"+jobId).val(),true);
                           },
                           Cancel: function() {
                               $( this ).dialog( "close" );
                           },
                           "Apply Selected Code(s)": function() {
                        	   var reqVals = [];
                        	   $(".rateitemclass").each(function() {
                        		   reqVals.push($(this).attr('id'));
                        		});
                        	   var obj={
             	            			rateitems:new Array()
             	            			
             	            	}
             	            	obj["jobId"]=jobId;
                        	   obj["agencyId"]=$("#agencyId"+jobId).val();
							   var eFlag = false;
							   var str = '';
                               var ccval = '';
                               var actulPgs = '';
                               
                        	  for(var k in reqVals){
                        		  var obj1 = {
		                			};
                        		  var code = $.trim($("#jobrateitemcode"+reqVals[k]).val());
                        		  if( (code == 'cc' || code == 'cC' || code == 'Cc' || code == 'CC') && $("#jobrateitemselected"+reqVals[k]).is(":checked")){
                        			  ccval = $("#jobrateitemquantity"+reqVals[k]).val();
                        			  actulPgs = $("#jobrateitemcount"+reqVals[k]).val();
                        		  }
                        		  obj1["jobselected"] = $("#jobrateitemselected"+reqVals[k]).is(":checked"); 
                        		  obj1["rateItemId"] = $("#jobrateitemid"+reqVals[k]).val();
                        		  obj1["rateItemCode"] = ($("#jobrateitemcode"+reqVals[k]).val()).toUpperCase();
                        		  obj1["rateItemDesc"] = $("#jobrateitemdesc"+reqVals[k]).val();
                        		  obj1["quantity"] = $("#jobrateitemquantity"+reqVals[k]).val();
                        		  obj1["rateItemCount"] =  $("#jobrateitemcount"+reqVals[k]).val();
                        		  obj1["value"] =  $("#jobrateitemprice"+reqVals[k]).val();
                        		  obj1["rateItemrateunit"] = $("#jobrateitemrateunit"+reqVals[k]).val();
                        		  obj1["rateItemperunit"] =  $("#jobrateitemperunit"+reqVals[k]).val();
                        		  obj1["reimbursable"] =  $("#jobrateitemreimb"+reqVals[k]).is(":checked");
                        		  obj1["taxable"] = $("#jobrateitemtaxabl"+reqVals[k]).is(":checked"); 
                        		  obj1["newratecode"] = $("#jobrateitemperunit"+reqVals[k]).find("option:selected").text();
								  if($.trim(obj1["rateItemCode"]) == "")
								  {
									  str +='Code is Required.';
									  eFlag = true;
									 
								  }
								  if($.trim(obj1["rateItemCount"]) == "")
								  {
									  str +='Count is Required.';
									  eFlag = true;
								  }
								  if($.trim(obj1["quantity"]) == "")
								  {
									  str +='Quantity is Required.';
									  eFlag = true;
								  }
								  if($.trim(obj1["value"]) == "")
								  {
									str +='Value is Required.';
									eFlag = true;
								  }
								  else if(isNaN(obj1["value"]))
								  {
									  str +='Enter Numeric Value.';
									  eFlag = true;
								  }
								  $("#allservicreimErrorMSGdiv").html(str);
								  if(eFlag)
									  return;
								  
              	            	  obj.rateitems.push(obj1);
              	            	}  
                        	  $.ajaxSetup({
           	          		   jsonp: null,
           	          		   jsonpCallback: null
           	          		});

           	          	    $.ajax({
           	          		  type:'POST',
           	          		  url: 'qgl-log-detail-accounting.action?saveJobServices',
           	          		  dataType: 'json',
           	          		  data: {data:JSON.stringify(obj),type:type},
           	          			 
           	          		  success: function(result){
           	          			  if(result.length == 0){
           	          				$("#servicesreimform").dialog( "close" );
           	          			  if(ccval.length > 0){
       	          			    	$("#ccVal"+jobId).val(parseInt(ccval)+1);
       	          			        $("#ccValView"+jobId).html(parseInt(ccval)+1);
           	          			  }
           	          			   if($.trim(actulPgs).length > 0){
           	          			    $("#actulPgs"+jobId).val(parseInt(actulPgs));
           	          			    $("#actulPgsView"+jobId).html(parseInt(actulPgs));
           	          			   }
           	          			       saveSelectedJob(jobId,true);
           	          			    
           	          			  }
           	          			  else{
           	          				$("#allservicreimErrorMSGdiv").html(result).addClass("errorblockdiv");
           	          			    $("#allservicreimErrorMSGdivOuter").html(result).addClass("errorblockdiv");
           	          			  }	  
           	          		    
           	          		 },
           	          		  error:function() { 
           	          			  
           	          		  }
           	          	});	
                        		  
                        		  
                           }
                           
                       },
                       close: function() {

                       },
                       create:function () {
   				        $(this).closest(".ui-dialog")
   				            .find(".ui-button") // the first button
   				            .addClass("p-button");
   				    	}
                   });
                   
                   
                   
      		 },
      		  error:function() { 
      		
      		  }
      	});

        }
        $(document).ready(function(){
        	ajaxCallToGetMasterRateItems(1);
        	ajaxCallToGetMasterRateItems(2);
        	var totalCount = ${actionBean.jobCount};
            var pageNumber = ${actionBean.offset}+1;
            
            if(totalCount > 3 )
        	  displayPagination(pageNumber,totalCount);
        });
        function getSelectedPageJobs(pageid){
        	if(pageid > 0)
        	pageid = pageid -1;
        	window.location = "qgl-log-detail-accounting.action?offset="+pageid;
        }
        function displayPagination(selectedPage,totalCnt){

        	  var noOfPages = Math.ceil(totalCnt/3);
        	  var selectedPageNumber = 1 ;
        	  if(selectedPage !='')
        		  selectedPageNumber = selectedPage;

        		$(function() {			
        				
        				$("#paginationDiv").paginate({
        					count 		: noOfPages,
        					start 		: selectedPageNumber,
        					display     : 10,
        					border					: false,
        					text_color  			: '#888',
        					background_color    	: '#EEE',	
        					text_hover_color  		: 'black',
        					background_hover_color	: '#CFCFCF'
        				});
        		   });
        	}
        
        function setAuttyDate(id){
    		
    		var number = id.substring(11);
    		
    		var auttyDateId="#dueAuttyDt"+number;
			if($.trim($('#'+id).val()) == "")
			return;
    		 var newDate = new Date($('#'+id).val());
    		newDate.setDate(newDate.getDate() + 2);
    		var changedDate = (newDate.getMonth()+1)+"/"+newDate.getDate()+"/"+(newDate.getYear()+1900);
    		
    		$(auttyDateId).val(changedDate); 
    		
    	}
		

</script>
<link rel="stylesheet" media="all" type="text/css" href="${pageContext.request.contextPath}/css/jquery/overcast/jquery-ui-1.8.21.custom.css" />


<%--<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.7.2.min.js"></script>--%>
<%--<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-ui-1.8.21.custom.min.js"></script>--%>

		<!--<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/my-profile.css" />-->

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-pending.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/pagination.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-dialog-buttons.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-detail-accounting.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-accounting.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-detail-accounting.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.paginate.js"></script>
